package org.example.netty.protocol;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.example.utils.LogUtils;

import java.net.InetSocketAddress;

public class CutomProtobufClient {

    /**
     * 魔数
     */
    public static final int MAGIC = 52;

    /**
     * 版本
     */
    public static final int VERSION = 1;

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();

        EventLoopGroup clientGroup = new NioEventLoopGroup();

        bootstrap.group(clientGroup);

        // 异步Channel
        bootstrap.channel(NioSocketChannel.class);

        // 初始化处理器
        bootstrap.handler(new ChannelInitializer<SocketChannel>(){
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // 已经转成字节，所以无需在编码
            }
        });

        try {
            // 同步等待连接成功
            ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8081)).sync();
            LogUtils.info("服务端连接成功，开始写数据");
            Channel channel = future.channel();


            for (int i = 0; i < 100; i++) {
                MsgProtos.Msg msg = buildMsg(i, "hello , i am " + i);
                ByteBuf buf = Unpooled.buffer();
                byte[] contents = msg.toByteArray();
                buf.writeInt(MAGIC);
                buf.writeInt(VERSION);
                buf.writeInt(contents.length);
                buf.writeBytes(msg.toByteArray());
                channel.writeAndFlush(buf);
            }
            Thread.sleep(Integer.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            clientGroup.shutdownGracefully();
        }
    }

    public static MsgProtos.Msg buildMsg(int id, String content) {
        MsgProtos.Msg.Builder builder = MsgProtos.Msg.newBuilder();
        builder.setId(id);
        builder.setContent(content);
        return builder.build();
    }
}
